package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code18SetMatrixZeroes {

    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        boolean colFlag = false;

        for (int i = 0; i < m; i++) {
            // 先检查第一列是否包含 0
            if (matrix[i][0] == 0) {
                colFlag = true;
            }
            // 检查中间的 0, 扩散到第一行和第一列
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }

        // 从最后一行填
        for (int i = m - 1; i >= 0; i--) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
            // 第一列
            if (colFlag) {
                matrix[i][0] = 0;
            }
        }
    }

    public void setZeroes1(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        boolean rowFlag = false;
        boolean colFlag = false;

        for (int[] ints : matrix) {
            if (ints[0] == 0) {
                colFlag = true;
                break;
            }
        }
        for (int c = 0; c < n; c++) {
            if (matrix[0][c] == 0) {
                rowFlag = true;
                break;
            }
        }

        // 中间
        for (int r = 1; r < m; r++) {
            for (int c = 1; c < n; c++) {
                if (matrix[r][c] == 0) {
                    matrix[r][0] = matrix[0][c] = 0;
                }
            }
        }
        for (int r = 1; r < m; r++) {
            for (int c = 1; c < n; c++) {
                if (matrix[r][0] == 0 || matrix[0][c] == 0) {
                    matrix[r][c] = 0;
                }
            }
        }

        if (rowFlag) {
            for (int c = 0; c < n; c++) {
                matrix[0][c] = 0;
            }
        }
        if (colFlag) {
            for (int r = 0; r < m; r++) {
                matrix[r][0] = 0;
            }
        }
    }
}
